package cn.ainit.sys.config;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import cn.ainit.sys.config.thread.TaskThread;
import cn.ainit.sys.dz.entity.SysDzSource;
import cn.ainit.sys.menu.MenuController;
import cn.ainit.sys.menu.MenuManager;
import cn.ainit.sys.socket.MsgThread;


public class SysConfigController implements ApplicationListener<ContextRefreshedEvent>{
	
	private SysConfigService sysConfigService;
	
	@Resource
	public void setSysConfigService(SysConfigService sysConfigService) {
		this.sysConfigService = sysConfigService;
	}
	
	private MenuManager menuManager;
	@Resource
	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}
	
	//3、Java中Map转换为JSON字符串
	public void convertmaptojson(Map map) {
	 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); 
	 String json = gson.toJson(map).toLowerCase(); 
	}
	
	
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if(event.getApplicationContext().getParent() == null){
			System.out.println("initialise system......");
			//root application context 没有parent，他就是老大.  
	        //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
			//读取数据库中的转译方法
			//获取所有的对象信息（转译对象、表的主键、表的外键）
			//在项目中生成formatter.js
			String formatStr = getClass().getResource("/").getFile().toString() + ".."+File.separatorChar+".."+File.separatorChar+"js"+File.separatorChar+"formatter.js";
		    try {
				formatStr=java.net.URLDecoder.decode(formatStr,"utf-8");   //url中含有空格会出现乱码现象，此方式是是路径正常转译的
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			File file = new File(formatStr);
			FileWriter writer = null;
			BufferedWriter bwriter = null;
			try {
				writer = new FileWriter(file);
				bwriter = new BufferedWriter(writer);
		        //加载对照信息
		        List<SysDzSource> sources = new ArrayList<SysDzSource>();
		        sources = sysConfigService.loadAddDzSource();
		        StringBuffer scriptB = new StringBuffer("");
		        StringBuffer script = new StringBuffer("");
		        String dzIdStr = "";
		        scriptB.append("var tmpLL = new Array();");
		        for (int i = 0; i < sources.size(); i++) {
		        	try {
		        		MenuController.mapList.put(sources.get(i).getDzId(), menuManager.loadDzList(sources.get(i).getSqlText(),sources.get(i).getShowPk(),sources.get(i).getShowName()));
		        	} catch (Exception e) {
						System.out.println("对照信息"+sources.get(i).getDzId()+"配置不正确"+sources.get(i).getSqlText());
					}
		        	dzIdStr = sources.get(i).getDzId();
		        	scriptB.append(" var "+ dzIdStr + " = new Array();\n" );
		        	script.append("\n");
					script.append("function "+dzIdStr+"fmat(value){");
					script.append("\n");
					script.append("var tmpName = '';");
					script.append("\n");
					script.append("if(value == null || value == '')return '';");
					script.append("\n");
					script.append("value = value + '';");
					script.append("\n");
					script.append("var valueArr = value.split(';');");
					script.append("\n");
					script.append("for(var i = 0; i < valueArr.length; i++){");
					script.append("\n");
					script.append("for(var j=0; j<"+dzIdStr+".length; j++){");
					script.append("\n");
					script.append(" tmpLL = valueArr[i].split(':');");
					script.append("\n");
					script.append("if(tmpLL.length > 1){");
					script.append("\n");
					script.append("if ("+dzIdStr+"[j].ID == tmpLL[0]) {");
					script.append("\n");
					script.append("if (tmpName != '')tmpName += ';';");
					script.append("\n");
					script.append("tmpName += "+dzIdStr+"[j].NAME+':'+''+tmpLL[1];");
					script.append("\n");
					script.append("}continue;}");
					script.append("\n");
					//------------------------------------------------------------
					script.append("if ("+dzIdStr+"[j].ID == valueArr[i]){");
					script.append("\n");
					script.append("if(tmpName != '')tmpName += ';';");
					script.append("\n");
					script.append("tmpName += "+dzIdStr+"[j].NAME;");
					script.append("\n");
					script.append("}}}");
					script.append("\n");
					script.append(new String("if(tmpName == '')tmpName = value;".getBytes("UTF-8"),"GBK"));
					script.append("\n");
					script.append("return tmpName;}");
					script.append("\n");
				}
		        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); 
	        	String json = gson.toJson(MenuController.mapList).toLowerCase(); 
	        	MenuController.formatsStr=json;
		        bwriter.write(scriptB.toString());
		        bwriter.write(script.toString());
		        bwriter.flush();
		        bwriter.close();
	        } catch (Exception e) {    
	            e.printStackTrace();
	        }finally{
	        	try {
					bwriter.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
	        }
	        //执行任务线程
	        TaskThread tskTh = new TaskThread();
	        tskTh.start();
	        //执行消息提示线程
	        MsgThread msgThread = new MsgThread();
	        msgThread.start();
	        
		}
	};
}
